#include "sqlite3_api.h"
#include <stdio.h>
#include "common.h"

int Init_DB(sqlite3 **pDb, const char *pDBName)
{
	if (NULL == pDBName)
	{
		return SQ_ERROR;
	}

	int iResult = sqlite3_open((const char *)pDBName, pDb);
	if(SQLITE_OK != iResult)
	{
		return SQ_ERROR;
	}
	return SQ_OK;
}

int Close_DB(sqlite3 *pDb)
{
	if (NULL == pDb)
	{
		return SQ_ERROR;
	}

	int iResult = sqlite3_close(pDb);

	if(SQLITE_OK != iResult)
	{
		return SQ_ERROR;
	}
	pDb = NULL;
	return SQ_OK;
}


int ExecSQL(char *pSql, sqlite3 *pDb)
{
	if (NULL == pSql || strlen(pSql) <= 0 || NULL == pDb)
	{
		return SQ_ERROR;
	}
	char *pErrMsg = NULL;
	
	int iResult = sqlite3_exec(pDb, pSql, NULL, NULL, &pErrMsg); 
	if(SQLITE_OK != iResult)
	{
		printf("%s\n", pErrMsg);
		sqlite3_free(pErrMsg);
		return SQ_ERROR;
	}

	return SQ_OK;
}

int GetTable(char *pSql, char ***pTableResult, int *pRow, int *pColumn, sqlite3 *pDb)
{
	if (NULL == pSql || strlen(pSql) <= 0 || NULL == pTableResult || NULL == pRow || NULL == pColumn || NULL == pDb)
	{
		return SQ_ERROR;
	}
	char* pErrMsg = NULL;
	int iResult = sqlite3_get_table(pDb, pSql, pTableResult, pRow, pColumn,&pErrMsg);

	if (SQLITE_OK != iResult)
	{
		printf("%s\n", pErrMsg);
		sqlite3_free(pErrMsg);
		return SQ_ERROR;
	}


	return SQ_OK;
}

int ShowTable(char **presult, int row, int column)
{
	if(NULL == presult || row <= 0 || column <= 0)
	{
		return SQ_ERROR;
	}
	int index,i,j;
	index = column;
	for(i = 0; i < row; i++)
	{
		for(j = 0; j < column; j++)
		{
			printf(" %s = %s ",presult[j],presult[index]);
			index++;
		}
		printf("\n");
	}
	return SQ_OK;
}

void FreeTableResult(char **pTableResult)
{
	if (NULL != pTableResult)
	{
		sqlite3_free_table(pTableResult);
	}
}





